<template>
  <Layout>
    <section class="mb-5 show-card">
      <div class="card">
        本日舱位发布数
        <div style="font-size: 28px">
          {{ cabinStat.toDay || 0 }}
        </div>
      </div>
      <div class="card">
        本周舱位发布数
        <div style="font-size: 28px">
          {{ cabinStat.toWeek || 0 }}
        </div>
      </div>
      <div class="card">
        本月舱位发布数
        <div style="font-size: 28px">
          {{ cabinStat.toMonth || 0 }}
        </div>
      </div>
      <div class="card">
        合计舱位发布数(2022-03-03~至今）
        <div style="font-size: 28px">
          {{ cabinStat.toAll || 0 }}
        </div>
      </div>
    </section>
    <section class="mb-5 bg-white chart-wrapper">
      <div class="title-line">
        <span class="title">数据趋势</span>
        <el-date-picker
          v-model="dataTrendParam.__dateRange$fromDate$toDate"
          size="small"
          :clearable="false"
          type="daterange"
          value-format="yyyy-MM-dd"
          unlink-panels
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="dataTrendOptions"
        />
      </div>
      <div
        class="flex"
        style="margin-top: 10px"
      >
        <div class="chart-container">
          <div class="title">
            舱位发布趋势
          </div>
          <div
            id="cabin-trend"
            ref="cabinTrend"
          />
        </div>
        <div
          class="chart-container"
          style="margin: 0 10px"
        >
          <div class="title">
            用户新增趋势
          </div>
          <div
            id="user-trend"
            ref="userTrend"
          />
        </div>
        <div class="rank-container">
          <div class="title">
            舱位发布次数排名
          </div>
          <div
            v-for="(item, index) in pushRank"
            :key="index"
            class="flex justify-between"
            style="margin-bottom: 3px"
          >
            <el-tooltip
              :content="item.compName || item.corpId"
              placement="left"
              effect="light"
            >
              <div class="no-wrap-text flex">
                <div style="min-width: 30px">
                  {{ index + 1 }}.
                </div>
                {{ item.compName || item.corpId }}
              </div>
            </el-tooltip>
            <span>{{ item.pushTime }}</span>
          </div>
        </div>
      </div>
    </section>
    <section class="mb-5 bg-white chart-wrapper">
      <div
        class="title-line flex justify-between"
        style="margin-bottom: 10px"
      >
        <div>
          <span class="title">历史统计</span>
          <el-date-picker
            v-model="historyStatParam.__dateRange$fromDate$toDate"
            size="small"
            :clearable="false"
            type="daterange"
            value-format="yyyy-MM-dd"
            unlink-panels
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="dataTrendOptions"
          />
        </div>
        <div>
          <el-button
            size="small"
            type="primary"
            @click="clickSearch"
          >
            查询
          </el-button>
          <el-button
            size="small"
            @click="resetTime"
          >
            重置
          </el-button>
          <el-button
            :disabled="loading"
            size="small"
            type="primary"
            @click="clickExport"
          >
            导出
          </el-button>
        </div>
      </div>
      <el-table
        :data="historyData"
        border
      >
        <el-table-column
          prop="pushDate"
          label="日期"
        />
        <el-table-column
          prop="pushCount"
          label="发布舱位数量"
        />
        <el-table-column
          prop="pushEnterpriseNumber"
          label="发布的企业数"
        />
        <el-table-column
          prop="pushUserNumber"
          label="发布的用户数"
        />
        <el-table-column
          prop="newEnterpriseNumber"
          label="新增发布企业数"
        />
        <el-table-column
          prop="totalEnterpriseNumber"
          label="累计发布企业数"
        />
        <el-table-column
          prop="newUserNumber"
          label="新增发布用户数"
        />
        <el-table-column
          prop="totalUserNumber"
          label="累计发布用户数"
        />
      </el-table>
      <div class="text-center py-4">
        <el-pagination
          v-model:current-page="historyStatParamTrue.num"
          background
          :total="historyTotal"
          :page-size="historyStatParamTrue.size"
          @current-change="getHistoryStat"
        />
      </div>
    </section>
  </Layout>
</template>

<script>
import Layout from '@/layout/index.vue'
import {
    cabinStatMap,
    cabinPushTrend,
    cabinUserIncreaseTrend,
    cabinPushRank,
    cabinHisStat,
    cabinHisExport
} from '@/api/cabin'
import dayjs from 'dayjs'
import * as echarts from 'echarts'
export default {
    name: 'CabinData',
    components: { Layout },
    props: {},
    data() {
        return {
            loading: false,
            cabinStat: {},
            dataTrendParam: {
                __dateRange$fromDate$toDate: [
                    dayjs().startOf('week').add(1, 'day').format('YYYY-MM-DD'),
                    dayjs().format('YYYY-MM-DD')
                ],
                __dateFormat: 'YYYY-MM-DD'
            },
            historyStatParamTrue: {
                num: 1,
                size: 10
            },
            historyTotal: 0,
            historyData: [],
            historyStatParam: {
                __dateRange$fromDate$toDate: null,
                __dateFormat: 'YYYY-MM-DD'
            },
            dataTrendOptions: {
                disabledDate: (time) => {
                    let nowTime = Date.now()
                    return time.getTime() > nowTime
                },
                shortcuts: [
                    {
                        text: '本日',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            picker.$emit('pick', [start, end])
                        }
                    },
                    {
                        text: '本周',
                        onClick(picker) {
                            const end = new Date()
                            const start = dayjs().startOf('week').add(1, 'day')
                                .$d
                            picker.$emit('pick', [start, end])
                        }
                    },
                    {
                        text: '本月',
                        onClick(picker) {
                            const end = new Date()
                            const start = dayjs().startOf('month').$d
                            picker.$emit('pick', [start, end])
                        }
                    },
                    {
                        text: '本年',
                        onClick(picker) {
                            const end = new Date()
                            const start = dayjs().startOf('year').$d
                            picker.$emit('pick', [start, end])
                        }
                    },
                    {
                        text: '最近7天',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 7
                            )
                            picker.$emit('pick', [start, end])
                        }
                    },
                    {
                        text: '最近30天',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 30
                            )
                            picker.$emit('pick', [start, end])
                        }
                    },
                    {
                        text: '最近90天',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 90
                            )
                            picker.$emit('pick', [start, end])
                        }
                    },
                    {
                        text: '最近365天',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 365
                            )
                            picker.$emit('pick', [start, end])
                        }
                    },
                    {
                        text: '最近666天',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 666
                            )
                            picker.$emit('pick', [start, end])
                        }
                    }
                ]
            },
            pushTrendChart: null,
            userTrendChart: null,
            pushRank: []
        }
    },
    computed: {},
    watch: {
        'dataTrendParam.__dateRange$fromDate$toDate': {
            handler(n) {
                if (!n) {
                    this.dataTrendParam.__dateRange$fromDate$toDate = [
                        dayjs()
                            .startOf('week')
                            .add(1, 'day')
                            .format('YYYY-MM-DD'),
                        dayjs().format('YYYY-MM-DD')
                    ]
                }
                this.getPushTrend()
                this.getUserTrend()
                this.getPushRank()
            },
            immediate: true
        }
    },
    mounted() {
        this.getCabinStat()
        this.getHistoryStat()
        this.pushTrendChart = echarts.init(this.$refs.cabinTrend)
        this.userTrendChart = echarts.init(this.$refs.userTrend)
    },
    methods: {
        async clickExport() {
            if (!this.historyStatParamTrue.__dateRange$fromDate$toDate) {
                this.$message.warning('请选择时间段，点击查询后再尝试导出')
                return
            }
            try {
                this.loading = true
                let res = await cabinHisExport(this.historyStatParamTrue)
                const url = window.URL.createObjectURL(
                    new Blob([res], {
                        type:
                            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                    })
                )
                const link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute(
                    'download',
                    `舱位数据历史统计_${dayjs().format(
                        'YYYY-MM-DD_HH_mm_ss'
                    )}.xlsx`
                )
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
            } catch (e) {
                console.log(e)
            } finally {
                this.loading = false
            }
        },
        clickSearch() {
            this.historyStatParamTrue = {
                ...this.historyStatParamTrue,
                ...this.historyStatParam
            }
            this.getHistoryStat()
        },
        resetTime() {
            this.historyStatParam.__dateRange$fromDate$toDate = null
        },
        async getHistoryStat() {
            let res = await cabinHisStat(this.historyStatParamTrue)
            this.historyData = res.data.records
            this.historyTotal = res.data.total
        },
        async getCabinStat() {
            let res = await cabinStatMap()
            this.cabinStat = res?.data || {}
        },
        async getPushRank() {
            let res = await cabinPushRank(this.dataTrendParam)
            this.pushRank = res.data.slice(0, 10)
        },
        async getPushTrend() {
            let res = await cabinPushTrend(this.dataTrendParam)
            // res.data = []
            // for (let index = 0; index < 200; index++) {
            //     res.data.push({
            //         pushCount: Math.random().toFixed(2) * 100,
            //         pushDate: dayjs('2021-02-24')
            //             .add(index, 'day')
            //             .format('YYYY-MM-DD'),
            //         pushEnterpriseNumber: Math.random().toFixed(2) * 100,
            //         pushUserNumber: Math.random().toFixed(2) * 100,
            //     })
            // }
            if (!this.$refs.cabinTrend) return
            const option = {
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['发布舱位数量', '发布的企业数', '发布的用户数']
                },
                grid: {
                    left: '5%',
                    right: '4%',
                    bottom: '1%',
                    containLabel: true
                },
                dataZoom: {
                    type: 'slider',
                    backgroundColor: 'rgba(47,69,84,0)',
                    handleSize: '100%'
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: res.data.map((i) => i.pushDate),
                    axisLabel: {
                        // interval: 0,
                        rotate: 60
                    }
                },
                yAxis: {
                    type: 'value',
                    splitNumber: 1
                },
                series: [
                    {
                        name: '发布舱位数量',
                        type: 'line',
                        // stack: 'Total',
                        data: res.data.map((i) => i.pushCount)
                    },
                    {
                        name: '发布的企业数',
                        type: 'line',
                        // stack: 'Total',
                        data: res.data.map((i) => i.pushEnterpriseNumber)
                    },
                    {
                        name: '发布的用户数',
                        type: 'line',
                        // stack: 'Total',
                        data: res.data.map((i) => i.pushUserNumber)
                    }
                ]
            }
            this.pushTrendChart.setOption(option)
        },
        async getUserTrend() {
            let res = await cabinUserIncreaseTrend(this.dataTrendParam)
            // res.data = []
            // for (let index = 0; index < 200; index++) {
            //     res.data.push({
            //         pushDate: dayjs('2021-02-24')
            //             .add(index, 'day')
            //             .format('YYYY-MM-DD'),
            //         newEnterpriseNumber: Math.random().toFixed(2) * 100,
            //         newUserNumber: Math.random().toFixed(2) * 100,
            //     })
            // }
            if (!this.$refs.userTrend) return
            const option = {
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['新增发布企业数', '新增发布用户数']
                },
                grid: {
                    left: '5%',
                    right: '4%',
                    bottom: '1%',
                    containLabel: true
                },
                dataZoom: {
                    type: 'slider',
                    backgroundColor: 'rgba(47,69,84,0)',
                    handleSize: '100%'
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: res.data.map((i) => i.pushDate),
                    axisLabel: {
                        // interval: 0,
                        rotate: 60
                    }
                },
                yAxis: {
                    type: 'value',
                    splitNumber: 1
                },
                series: [
                    {
                        name: '新增发布企业数',
                        type: 'line',
                        // stack: 'Total',
                        data: res.data.map((i) => i.newEnterpriseNumber)
                    },
                    {
                        name: '新增发布用户数',
                        type: 'line',
                        // stack: 'Total',
                        data: res.data.map((i) => i.newUserNumber)
                    }
                ]
            }
            this.userTrendChart.setOption(option)
        }
    }
}
</script>
<style lang="scss" scoped>
.no-wrap-text {
    cursor: default;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-right: 10px;
    &:hover {
        color: #006aff;
    }
}
.title {
    font-size: 18px;
}
.chart-wrapper {
    padding: 10px;
    width: calc(100vw - 200px);
    @media screen and (max-width: 1492px) {
        width: 100%;
    }
}
.chart-container {
    min-width: 520px;
    height: 320px;
    .title {
        margin-bottom: 10px;
    }
    #cabin-trend {
        height: 280px;
    }
    #user-trend {
        height: 280px;
    }
}
.rank-container {
    flex: 1;
    min-width: 250px;
    height: 280px;
    .title {
        margin-bottom: 10px;
    }
}
.title-line {
    line-height: 32px;
    .title {
        margin-right: 20px;
    }
}
.show-card {
    display: grid;
    grid-template-columns: repeat(4, 23%);
    grid-template-rows: auto;
    column-gap: 20px;
    max-width: 1200px;
    .card {
        display: flex;
        flex-direction: column;
        justify-content: center;
        text-align: center;
        background: white;
        aspect-ratio: 16/9;
    }
}
</style>
